<?php
/**
 * 合作伙伴管理
 * @author cjli
 *
 */ 
class PartnerAction extends HomeAction
{

	public function _initialize()
	{
		parent::_initialize();
		global $user;
		if(isset($user['is_partner']) && $user['is_partner'] == 0){
			if(!in_array(ACTION_NAME,array('index', 'login', 'login_')))
		        redirect(url('user/index'));
		}		
	} 
	 
	public function index()
	{
		$this->login_();
	}

	//老链接做301
	public function login()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_login_partner'),
			//'docKeywords' => L('meta_keywords'),
			//'docDescription' => L('meta_description'),
		);
		$this->assign($data);

		$post = $_REQUEST;
		$src = isset($post['src']) ? trim($post['src']) : null;
		$this->assign('src', $src);
		//跳转到上一个页面
		$http = $_SERVER['HTTP_REFERER'];
		$this->assign('http',$http);
		if(isset($post['dosubmit']))
		{

			if(C('vcode_login') == 1 && isset($post['login_vcode'])){
				if($_SESSION['login_vcode'] != strtolower($post['login_vcode'])){
					$this->error(L('_VERIFICATION_ERROR_'));
				}
			}

			$username = trim($post['username']);
			$password = trim($post['password']);
			$goback = $post['goback'];
			//登录验证
			if(!$user_id = UserModel::validate_user($username, $password, 1)){
				$this->error(L('_LOGIN_FAILED_THE_USER_NAME_OR_PASSWORD_ERROR_'), url('partner/login',array('loginbox'=>'show')));
			}

			//获取用户信息
			$user_info = UserModel::get_user_info($user_id);
			if(!$user_info['disabled']){
				$this->error(L('_MEMBER_ACCOUNT_HAS_BEEN_DISABLED_PLEASE_CONTACT_YOUR_ADMINISTRATOR_'));
			}
			session('user_id', $user_id);

			// //更新用户数据
			UserModel::setLogin($user_id);

			// //合并购物车
			// CartModel::mergeCart($user['sid']);

			// //合并身型数据
			// AttributeModel::mergeMeasure($user['sid']);

			// //删除游客登陆
			// session('countiue_buy', null);
			if($src){
				redirect(base64_decode($src));
			}else if($goback){
				redirect($goback);
			}else{
				redirect('/partner/center');
			}
		}else{
			$this->display('login');
		}
	}	
	//会员登录
	public function login_()
	{
		global $user;
		$data = array(
    		'docTitle' => L('meta_title_login_partner'),
    		//'docKeywords' => L('meta_keywords'),
    		//'docDescription' => L('meta_description'),
    	);
		$this->assign($data);

		$post = $_REQUEST;
		$src = isset($post['src']) ? trim($post['src']) : null;
		$this->assign('src', $src);
		//跳转到上一个页面
		$http = $_SERVER['HTTP_REFERER'];
		$this->assign('http',$http);
		
		// $src_login = strstr(base64_decode($src), 'measure/cart');
		// $this->assign('src_login', $src_login);
		// $this->assign('facebookLoginUrl',$this->facebook_login());

		// if(UserModel::logged())
		// {   
		// 	redirect($src ? base64_decode($src) : url('partner/center'));
		// }
		// else
		if(isset($post['dosubmit']))
		{

			if(C('vcode_login') == 1 && isset($post['login_vcode'])){
				if($_SESSION['login_vcode'] != strtolower($post['login_vcode'])){
					$this->error(L('_VERIFICATION_ERROR_'));
				}
			}
			
			$username = trim($post['username']);
			$password = trim($post['password']);
			$goback = $post['goback'];
			//登录验证
			if(!$user_id = UserModel::validate_user($username, $password, 1)){
				$this->error(L('_LOGIN_FAILED_THE_USER_NAME_OR_PASSWORD_ERROR_'), url('partner/login',array('loginbox'=>'show')));
			}

			//获取用户信息
			$user_info = UserModel::get_user_info($user_id);
			if(!$user_info['disabled']){
				$this->error(L('_MEMBER_ACCOUNT_HAS_BEEN_DISABLED_PLEASE_CONTACT_YOUR_ADMINISTRATOR_'));
			}
			session('user_id', $user_id);
			
			// //更新用户数据
			UserModel::setLogin($user_id);

			// //合并购物车
			// CartModel::mergeCart($user['sid']);
			
			// //合并身型数据
			// AttributeModel::mergeMeasure($user['sid']);
            
			// //删除游客登陆
			// session('countiue_buy', null);
			if($src){
                redirect(base64_decode($src));
			}else if($goback){
				redirect($goback);
			}else{
				redirect('/partner/center');
			}
		}else{
			$this->display('partner_login');
		}
	}
	
    public function update_order(){
        global $user,$language_id;
        $order_id = intval($_GET['oid']);
        if(IS_POST && $order_id){

            if($_POST['surplus_money'] > 0){
                $surplus_money = isset($_POST['surplus_money']) ? floatval($_POST['surplus_money']) : 0;
                $currency = isset($_SESSION['currency']) ? $_SESSION['currency'] : C('currency');

                //如果使用余额小于会员余额
                if($user && isset($user['user_money']) && $user['user_money']>0){
                    $surplus_money = $user['user_money']<$surplus_money ? $user['user_money'] : $surplus_money;
                }else{
                    $surplus_money = 0;
                }
                $order_info = M('orders')->where('id ='.$order_id.' and user_id ='.$user['id'])->find();

                //扣除会员的余额
                if($surplus_money && $user['id']){
                    UserModel::log_account_change($user['id'],(-1)*$surplus_money,0,0,0,L('_ORDER_USE_BALANCE_PAYMENT_').' '.L('_THE_ORDER_NUMBER_IS_').' '.$order_info['order_sn'],UserModel::ACT_PAY);
                }
                $pay_amount = $order_info['pay_amount'] - $surplus_money;
                if($order_info['surplus_money'] > 0){//之前使用过余额下单 再次使用余额支付
                    $surplus_money = $order_info['surplus_money'] + $surplus_money;
                }
                $data = array(//更新订单状态
                    'id'=> $order_id,
                    'surplus_money' => $surplus_money,
                    'pay_amount'  => $pay_amount,
                    'currency'  => $currency,
                    'language_id'  => $language_id,
                );

                if($pay_amount ==  0){//全部余额支付
                	    //支付通知邮件
		      			$email_template = UserModel::get_email_template_info('orderPayEmail', $order_info['language_id']);
						if($email_template){
							$mailInstance = new EmailModel();
							$content = $mailInstance->replaceMail($email_template['content'], $order_info);
							$title = $mailInstance->replaceMail($email_template['title']);
							$mailInstance->sendMail($order_info['delivery_email'], $title, $content,'html','bcc');
						}

                        $data['payment_status'] = OrderModel::PAY_PAYED;
                        $data['order_status'] = OrderModel::ORDER_CONFIRMED;
                        $data['payment_time'] = time();
                        OrderModel::gift_email($order_id);//giftcard发送邮件
                }
                if($surplus_money > 0){
                        M('orders')->save($data);
                }
            }
            //更新订单支付方式
            if(isset($_POST['payment_method']) && $_POST['payment_method']){
	            $data = array(
	                'id'=> $order_id,
	                'payment_method'  => $_POST['payment_method'],
	            );
	            M('orders')->save($data);  
            }      
            redirect(url('cart/ordersuccee', 'oid='.$order_id));
        }
    }
	

	
	//会员登出
	public function logout()
	{
		UserModel::logout();
		$post = $_REQUEST;
		$src = isset($post['src']) ? trim($post['src']) : null;
		if($src){
            redirect(base64_decode($src));
		}else{
			redirect(url(''));
		}
	}
	
	//会员中心
	public function center()
	{	
		global $user;
		
		$this->checklogin();
		
		$templatefile = THEMES_PATH.'partner/partner_index.phtml';
		$this->assign('templatefile', $templatefile);
		
	    $_SESSION['center_type'] = 102;

        $user_id = $user['id'];
        $nowTime = time();
        $start_time = date('Y-m-d 00:00:00' ,$nowTime); 

        //新闻通知
 		$articleWhere = array(
 			'catid' => 2142,
 			'orderby' => 'id desc',
 			);
		$articleList = ArticleModel::get_article_list($articleWhere, 0, 10);
		//print_r($articleList);exit;
        $this->assign('articleList', $articleList);	

        //地址(客户)数量
		$address_list = UserModel::get_address_list($user_id, array('start_time' =>$start_time));
		$this->assign('address_count', intval($address_list));
        //今日订单数查询
        $orderWhere = array(
			'order_status' => array('neq',OrderModel::ORDER_DEL),
            'user_id' => $user_id,
            'start_time' => $start_time,
        	);

		$order_count = OrderModel::get_order_count($orderWhere);
		$this->assign('order_count', $order_count);	
        //今日订单金额查询
        $orderField = 'sum(order_amount) as order_amount';
		$order_res = OrderModel::get_order_field($orderWhere, $orderField);
		//echo M()->getLastSQL();exit;
		$order_field['order_amount'] = $order_res['order_amount'];
        //今日订单已支付金额查询
        $orderField = 'sum(pay_amount) as pay_amount';
        $orderWhere['payment_status'] = OrderModel::PAY_PAYED;
        $orderWhere['payment_time'] = array('egt',strtotime($start_time));
        unset($orderWhere['start_time']);
		$order_res = OrderModel::get_order_field($orderWhere, $orderField);
		$order_field['pay_amount'] = $order_res['pay_amount'];

		$this->assign('order_field', $order_field);	
        $this->assign('robots','noindex');
		$this->display('usercenter');
	}
	
	//会员信息
	public function info()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_user_info'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		//$this->checklogin();
	if(UserModel::logged()){
		$_SESSION['center_type'] = 7;

		if($_POST['dosubmit']){
			$post = $_POST;
//			import('COM.Validate');
//			$email = trim($post['email']);
//			if(empty($email) || !Validate::email($email)){
//				$this->error(L('_EMAIL_FORMAT_ERROR_'), url('user/info'));
//			}
//			if(UserModel::validate_email_only($email, $user['id'])){
//				$this->error(L('_EMAIL_ALREADY_EXISTS_'), url('user/info'));
//			}
			if ( (isset($_FILES['up_user_photo']) && $_FILES['up_user_photo']['tmp_name'])){
				$info = $this->upload('user');
				if(is_array($info)) {// 上传成功 获取上传文件信息
					if(isset($info['up_user_photo'])){
						$post['user_photo'] = UPLOAD_PATH . $info['up_user_photo']['savename'];
					}
				}else{
					$this->error($info);
				}
			}
			
			if(isset($post['data']['country_id']) && $post['data']['country_id']){
				$area_info = SiteModel::get_region_info($post['data']['country_id']);
	  		if($area_info){
	  			$post['data']['country'] = $area_info['name'];
	  		}
			}
			
			$result = UserModel::update_user($user['id'], $post);
			
			if($result){
				$this->success(L('_OPERATION_SUCCESS_'), url('partner/info'));
			}else{
				$this->error(L('_OPERATION_FAIL_'), url('partner/info'));
			}
		}else{
			$countryList = SiteModel::get_country_list();
			$countryName = '';
			if($countryList){
				foreach($countryList as $country){
					if($user['data']['country_id'] == $country['id']){
						$countryName = $country['name'];
					}
				}
			}
			$this->assign('countryName', $countryName);
			$this->assign('countryList', $countryList);
			$this->assign('user', $user);
			$templatefile = THEMES_PATH.'partner/partner_account_detail.phtml';
			$this->assign('templatefile', $templatefile);			
		}
		}else{
			redirect($src ? base64_decode($src) : url('partner/login'));		
		}
		$this->display('usercenter');
	}
	
	//会员中心修改密码
	public function user_password()
	{
		global $user;
		
		$this->checklogin();
		
		if($_POST['dosubmit']){
			
			$oldpassword = trim($_POST['oldpassword']);
			$userInfo = UserModel::get_user_info($user['id']);
			list($md5password, $rand_salt) = UserModel::generate_password($oldpassword, $userInfo['rand_salt']);
			if($userInfo['password'] != $md5password){
				$this->error(L('_THE_OLD_PASSWORD_ERROR_'), url('partner/info'));
			}
			$password = $_POST['password'];
			import('COM.Validate');
			$validate = new Validate();
			if(empty($password) || !$validate->len($password,6,20)){
				$this->error(L('_THE_PASSWORD_SHOULD_BE_BETWEEN_6_20_'));
			}
			if(empty($_POST['confirm_password']) || $_POST['confirm_password'] != $password){
				$this->error(L('_ENTER_THE_PASSWORD_TWICE_INCONSISTENT_'));
			}
			$data = array(
				'password' => $password,
			);
			if(UserModel::update_user($userInfo['id'], $data)){
				$this->success(L('_PASSWORD_EDIT_SUCCESS_'), url('partner/info'));
			}else{
				$this->error(L('_PASSWORD_EDIT_FAILED_'), url('partner/info'));
			}
		}else{
             //跳转到会员资料页面
            redirect(url('partner/info'));
		}
	}
	

	//资金管理
	public function user_account()
	{
		global $user;
		if(UserModel::logged()){
			$_SESSION['center_type'] = 9;
			$user_account_db = D('user_account');
			$user_account_db->where('user_id='. $user['id']);
			$count = $user_account_db->count();
			require THEMES_PATH.'page.php';
			$Page = new Page($count,10);
			$pageShow = $Page->show();
			
            $pageShow = preg_replace("/\/_\/(\d+)'/is", "'", $pageShow);
            $pageShow = preg_replace("/href='\/partner\/user_account\/p\/(\d+)'/is", "href='javascript:;' onclick='accountShow($1);'", $pageShow);
			$this->assign('pageShow', $pageShow);

			$user_account_db->where('user_id='. $user['id']);
			$user_account_db->limit($Page->firstRow.','.$Page->listRows);
			$accountList = $user_account_db->select();
			$this->assign('accountList', $accountList);
			$this->assign('user', $user);
			$this->display('user_account');
		}
	}

	//账户记录明细
	public function account_detail()
	{
		global $user;
		if(UserModel::logged()){
			$_SESSION['center_type'] = 9;
			$user_account_db = D('user_account_log');
			$user_account_db->where('user_id='. $user['id']);
			$count = $user_account_db->count();
			require THEMES_PATH.'page.php';
			$Page = new Page($count,10);
			$pageShow = $Page->show();
			$this->assign('pageShow', $pageShow);

            $pageShow = preg_replace("/\/_\/(\d+)'/is", "'", $pageShow);
            $pageShow = preg_replace("/href='\/partner\/account_detail\/p\/(\d+)'/is", "href='javascript:;' onclick='accountShow($1);'", $pageShow);
			$this->assign('pageShow', $pageShow);
			
			$user_account_db->where('user_id='. $user['id']);
			$user_account_db->limit($Page->firstRow.','.$Page->listRows);
			$accountList = $user_account_db->order('id desc')->select();
			$this->assign('accountList', $accountList);
			$this->assign('user', $user);
			$this->display('account_detail');
		}
	}	
	
	//订单列表
	public function order_list()
	{
		global $user;
		$data = array(
    		'docTitle' => L('meta_title_order_list'),
    		'docKeywords' => L('meta_keywords'),
    		'docDescription' => L('meta_description'),
    	);
		$this->assign($data);		
		//$this->checklogin();
		if(UserModel::logged()){
		if($_GET['order_status']==-1){
			$_SESSION['center_type'] = 2;
		}else{
			$_SESSION['center_type'] = 1;
		}
		
		
		$post = array_merge($_GET,$_POST);
        $where['orders.order_status'] = array('neq','-2');

		if(!isset($post['is_gift_orders']) || (isset($post['is_gift_orders']) && $post['is_gift_orders']==0)){
			$where['orders.is_gift_orders'] = 0; //非礼品订单
		}else{
			$where['orders.is_gift_orders'] = 1; //礼品订单
			$_SESSION['center_type'] = 104;
		}


		$where['orders.user_id'] = $user['id'];
		if($post['order_status'] != ''){
			$order_status = intval($post['order_status']);
			if($order_status == 100) 
				$order_status = 0;
			$where['order_status'] = $order_status;
		}
		if($post['payment_status'] != ''){
			$payment_status = intval($post['payment_status']);
			if($payment_status == 100) 
				$payment_status = 0;
			$where['payment_status'] = $payment_status;
		}
		if($post['shipping_status'] != ''){
			$where['shipping_status'] = intval($post['shipping_status']);
		}
		if($post['order_sn'] != ''){
			$order_sn = trim($post['order_sn']);
			$sqlstr = "(order_sn like '%".$order_sn."%' ";
			$sqlstr .= " or concat(delivery_first_name,delivery_last_name) like '%".str_replace(" ","",$order_sn)."%')";
			$where['_string'] = $sqlstr;
			$this->assign('order_sn', $order_sn);
		}
		if($post['start_time']){
			$where['start_time'] = array('gt', strtotime($post['start_time']));
		}
		if($post['end_time']){
			$where['start_time'] = array('lt', strtotime($post['end_time']));
		}
		$order_db = D('orders');
		$order_item_db = D('orders_items');
		
		//分页
		$order_db->where($where);
		$count = $order_db->count();//总记录数
		require THEMES_PATH.'page.php';// 导入分页类
		$Page = new Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数
		$pageShow = $Page->show();// 分页显示输出
		$this->assign('pageShow', $pageShow);
		
		$order_db->field('orders.id,order_sn,order_amount,
			pay_amount,order_status,payment_status,shipping_status,
			start_time, comment.id as is_comment, payment_method,
			delivery_first_name,delivery_last_name,delivery_email,
			delivery_phone,delivery_mobile,delivery_cid,delivery_pid,
            delivery_country,delivery_province,delivery_city,delivery_address,
            delivery_address2,delivery_address3,delivery_postcode,delivery_time,
            delivery2_first_name,delivery2_last_name,delivery2_email,delivery2_phone,
            delivery2_cid,delivery2_country,delivery2_province,delivery2_city,
            delivery2_address,delivery2_address2,delivery2_address3,delivery2_postcode,orders.is_gift_orders');
		$order_db->order('orders.id DESC');
		$order_db->limit($Page->firstRow.','.$Page->listRows);
		$order_db->join('`comment` ON comment.order_id = orders.id');
		$order_db->group('orders.id');
		$order_db->where($where);
		$ordersList = $order_db->select();
		//echo M()->getLastSql();exit;
		//var_dump($ordersList);
		if($ordersList){
			foreach ($ordersList as &$row){
				
				$order_item_db->field('product.yushou_end_time,product.weikuan_time,product.product_type,car_type');
				$order_item_db->join('product ON product.id = orders_items.product_id');
				$order_item_db->where(array('order_id' => $row['id']));
				$productInfo = $order_item_db->find();
				if($productInfo){
					$row['yushou_end_time'] 	= $productInfo['yushou_end_time'];
					$row['weikuan_time'] 		= $productInfo['weikuan_time'];
					$row['product_type'] 		= $productInfo['product_type'];
					$row['car_type'] 			= $productInfo['car_type'];
				}
				$pay_return_db = D('orders_pay_return');
				$returnInfo = $pay_return_db->where('order_sn="'.$row['order_sn'].'" AND car_type=1')->find();
				//判断是否已申请退款
				if($returnInfo){
					$row['pay_return'] = 1;
					if($returnInfo['status']==2)
						$row['return_status'] = L('refunded');//已退款
					else
						$row['return_status'] = L('a_refund_of');//退款中
				}else{
					$row['pay_return'] = 0;
				}
				//支付按钮
				if(!in_array($row['order_status'], array(OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL))
					    && $row['payment_status'] == OrderModel::PAY_UNPAYED && $row['is_gift_orders']!=1){  //如果是礼品  不需要支付按钮
                    $paymentSubmit  = '';
                    $paymentSubmit .= '<form id="frm" method="post" action="'.url('cart/ordersuccee',array('oid'=>$row['id'])).'" target="_blank">';
					$paymentSubmit .= '<input class="pay_button" type="submit" value="'.L('_PAY_NOW_').'">';
					$paymentSubmit .= '</form>';
					$row['paymentSubmit'] = $paymentSubmit;
				}
				if($row['order_status'] == OrderModel::ORDER_COMPLETE){
                   $orders_items = D('orders_items')->field('id')->where(array('order_id'=>$row['id']))->select();
                   $row['add_comment'] = false;
				   foreach ($orders_items as $orders_items_id) {
				        //是否评论过
				        $comment_where = array(
				        	'order_items_id'=>$orders_items_id['id'],
				        );
				        $comment_res = M('comment')->where($comment_where)->count();
				        if(!$comment_res){
				        	$row['add_comment'] = true;break;
				        }
				   }
				}
			}
			unset($row);
		}
		$this->assign('ordersList', $ordersList);

		if(!isset($post['is_gift_orders']) || (isset($post['is_gift_orders']) && $post['is_gift_orders']==0)){
			$templatefile = THEMES_PATH.'partner/partner_order_list.phtml'; //非礼品订单列表模板
		}else{
			$templatefile = THEMES_PATH.'partner/partner_gift_order_list.phtml'; //礼品订单列表模板
		}

		$this->assign('templatefile', $templatefile);
		//$osid = $_GET['order_status'];
		$order_result['osid'] = $post['order_status'];
		if($post['order_status'] >=0 && $post['order_status'] != NULL){
			$order_result['name'] = L(OrderModel::$orderStatus[$order_status]);
		}else{
			$order_result['name'] = L('any');
		}
		$payment_result['psid'] = $post['payment_status'];
		if($post['payment_status']>=0 && $post['payment_status'] != NULL){
			$payment_result['name'] = L(OrderModel::$paymentStatus[$payment_status]);
		}else{
			$payment_result['name'] = L('any');
		}
		//判断session是否存在，不存在查询商品总数量
		if(!isset($_SESSION['cart']['number'])){
			$cart_products_db = D('cart_products');
			$cartProductsInfo = $cart_products_db->where(array('user_id'=>$user['id']))->sum('qty');
			$_SESSION['cart']['number']=$cartProductsInfo;
		}
		$this->assign('order_result', $order_result);
		$this->assign('payment_result', $payment_result);
		}else{
			redirect($src ? base64_decode($src) : url('partner/login'));
		}
		$this->display('usercenter');
	}
	//会员取消订单
	public function order_cancel(){
		global $language_id,$user;
		$this->checklogin();
		$order_id = intval($_GET['oid']);
		$orderInfo = OrderModel::get_order_info($order_id);
        //过滤不合法的请求
        if($orderInfo['user_id'] != $user['id']){
            $this->error(L('_ERROR_ACTION_'), url('user/order_list')); 
            exit;
        }
        //var_dump($orderInfo);die;
        //只有订单是未确认，未支付状态 才能取消操作
        $post = array();
        if( ($orderInfo['order_status'] == OrderModel::ORDER_UNCONFIRMED) && ($orderInfo['payment_status'] == OrderModel::PAY_UNPAYED) ){
  			$post = array(
                'order_status' => OrderModel::ORDER_CANCELED,
  		    );
  		    $res = OrderModel::update_order_status($order_id, $post);
  		    if($res){
  		    	//如果订单有使用红包，则返回用户红包
  		    	$user_bonus_where = array(
  		    		'bonus_sn' => $orderInfo['order_sn'],
  		    		'used_time'  => array('gt',0),
  		    	);
                D('user_bonus')->where($user_bonus_where)->save(array('bonus_sn'=>0,'used_time'=>0));
                //释放优惠码
                $coupon_info = M('favorable')->where("coupon_code = '".$orderInfo['coupon_code']."'")->find();
                if($coupon_info['status'] == 0 || $coupon_info['count']){
                    if($coupon_info['type'] == 4 || $coupon_info['type'] == 2){//类型为2和4的是有使用限制的优惠码
                        $fdata['status'] = $coupon_info['type']; //
                        $fdata['usage_count'] = $coupon_info['usage_count'] + 1;//优惠码可使用次数+1
                    }else{
                            $fdata['status'] = 2;
                    }
                    $fdata['id'] = $coupon_info['id'];
                    M('favorable')->save($fdata);
                }
                //返回余额
                $surplus_money = floatval($orderInfo['surplus_money']);
                if($orderInfo['user_id'] > 0 && $surplus_money > 0){
                    //订单取消返回相应余额到账户
                    $tips = L('cancel_order').' '.$orderInfo['order_sn'];
				    UserModel::user_account_change($orderInfo['user_id'], $surplus_money, 0, 1, NULL, $tips, NULL);
				    UserModel::log_account_change($orderInfo['user_id'], $surplus_money, 0, 0 ,0, $tips, UserModel::ACT_SAVING);
                }
                
                //取消的原因
				$logData = array(
			  		'order_id' => $order_id,
				  	'order_status' => OrderModel::ORDER_CANCELED,
				  	'payment_status' => $orderInfo['payment_status'],
				  	'shipping_status' => $orderInfo['shipping_status'],
			  		'action_notice' => $this->_request('message') ? trim($this->_request('message')) : null,
			  		'action_name' => $user['email'],
			  		'pro_type' => 1,
				);
            	if(intval($this->_request('canceltype'))>0)
            	    $logData['type']     = $this->_request('canceltype');					

				OrderModel::insert_orders_log($logData);

                //发送取消订单邮件
				$mailInstance = new EmailModel();
				$email_template = UserModel::get_email_template_info('orderCancelEmail', $orderInfo['language_id']);
				if($email_template){
					$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
					$title = $mailInstance->replaceMail($email_template['title']);
					$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
				}
								
                //成功提示
                $this->success(L('order_canceled_ok'), url('partner/order_list')); 
                exit;
  		    }   	
        }
        $this->error(L('operation_failed'), url('partner/order_list'));  		        
	}
	//会员中心订单详细页
	public function order_info()
	{
		global $language_id,$user;
		$this->checklogin();
		
		$order_id = intval($_GET['oid']);
		$orderInfo = OrderModel::get_order_info($order_id);
		
        //过滤不合法的请求
        if($orderInfo['user_id'] != $user['id']){
            $this->error(L('_ERROR_ACTION_'), url('partner/order_list')); 
            exit;
        }
		$pay_return_db = D('orders_pay_return');
		$returnInfo = $pay_return_db->where('order_sn="'.$orderInfo['order_sn'].'" AND car_type=1')->find();
		//判断是否已申请退款
		if($returnInfo){
			$orderInfo['pay_return'] = 1;
			
			if($returnInfo['status']==2)
				$orderInfo['return_status'] = L('refunded');
			else
				$orderInfo['return_status'] = L('a_refund_of');
		}else{
			$orderInfo['pay_return'] = 0;
		}
		$order_item_db = D('orders_items');
		$order_item_db->field('product.yushou_end_time,product.weikuan_time,product.product_type,car_type');
		$order_item_db->join('product ON product.id = orders_items.product_id');
		$order_item_db->where(array('order_id' => $order_id));
		$productInfo = $order_item_db->find();
		$orderInfo['car_type'] = $productInfo['car_type'];
		$this->assign('yushou_end_time', $productInfo['yushou_end_time']);
		$this->assign('weikuan_time', $productInfo['weikuan_time']);
			
		if(!$orderInfo){
			$this->error(L('_ORDER_NO_EXIST_'), url('partner/order_list'));
		}
		$orderInfo['payment'] = PaymentModel::get_payment_info($orderInfo['payment_method']);
		//看用户可以使用多少积分支付
		$total_amount = $orderInfo['product_amount']+$orderInfo['payment_fee']+$orderInfo['shipping_fee'];
		$use_integral = UserModel::get_user_integral($total_amount);
		if(is_array($use_integral))
			list($total_integral, $integral_money) = $use_integral;
		$this->assign('total_integral', isset($total_integral) ? $total_integral : 0);
		$this->assign('integral_money', isset($integral_money) ? $integral_money : 0);
			
		//看用户可以使用多少红包
		$bonusList = UserModel::get_bonus_list();
		if($bonusList)
			$this->assign('bonusList', $bonusList);
		 //订单产品列表
		$orderInfo['productList'] = OrderModel::get_order_product_list($order_id);
		$measure_id = 0;
		//读取购物车中定制商品的定制信息
		foreach ($orderInfo['productList'] as $key => $order_items) {
			$attr = $order_items['original_attr'];
			if($order_items['custom_type'] == '2' && is_array($attr)){	
	            list($attributeList, $size_type) = CartModel::cart_attr_show($order_items['product_id'], serialize($attr));
			    $orderInfo['productList'][$key]['attributeList'] = $attributeList;
			    $orderInfo['productList'][$key]['size_type']     = $size_type;
		    }
			$measure_id = $order_items["measure_id"];
		}
		//获取身形数据
		if($measure_id){
			$user_measure_db = D('user_measure');
			$orderInfo['measure_data'] = $user_measure_db->find($measure_id);
		}

		//发货单列表
		$orderInfo['deliveryList'] = OrderModel::get_delivery_list($order_id);
		//支付按钮
		// if(!in_array($orderInfo['order_status'], array(OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL))
		// 	&& $orderInfo['payment_status'] == OrderModel::PAY_UNPAYED){
		// 	import('COM.Payment');
		// 	$paymentInstance = Payment::getInstance($orderInfo['payment_method']);
		// 	$payOrderInfo = $orderInfo;
		// 	$payOrderInfo['currency'] = isset($_SESSION['currency']) && $_SESSION['currency'] ? $_SESSION['currency'] : C('currency'); //币种
		// 	$payOrderInfo['pay_amount'] = currency($orderInfo['pay_amount'],null,false);
		// 	$paymentSubmit = $paymentInstance->getSubmitForm($payOrderInfo);
		// 	$this->assign('paymentSubmit', $paymentSubmit);
		// }
        //var_dump($paymentSubmit);die;
		$this->assign('orderInfo', $orderInfo);
		$user_money = M('users')->field('user_money')->where('id='.$user['id'])->find();
        $this->assign('user_money',$user_money['user_money']);
		$paymentList = PaymentModel::get_payment_list();
		$this->assign('paymentList', $paymentList);
		$shippingList = ShippingModel::get_shipping_list();
		$this->assign('shippingList', $shippingList);
		$countryList = SiteModel::get_country_list();
		$this->assign('countryList', $countryList);
		
		/*if($productInfo['car_type'] > 0)
			$templatefile = THEMES_PATH.'user/order_info02.phtml';
		else*/
		if($orderInfo['is_gift_orders']==1){
			$templatefile = THEMES_PATH.'partner/gift_order_info.phtml';
		}else{
			$templatefile = THEMES_PATH.'partner/order_info.phtml';
		}

		$this->assign('templatefile', $templatefile);
		$this->display('usercenter');
	}
	

	
	//(联系人)配送地址列表
	public function customer()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_address_list'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);		
		//$this->checklogin();
		if(UserModel::logged()){
			$_SESSION['center_type'] = 13;
			if($_POST['dosubmit']){
				if($address_id = UserModel::update_user_address($user['id'], $_POST)){
					$_POST['address_id'] = $address_id;
					$_POST['measure_name'] = $_POST['delivery_first_name'].' '.$_POST['delivery_last_name'];
					MeasureModel::add_measure_data($_POST);
					//自动把合作伙伴下面的客户新增成网站会员
					UserModel::partner_user_add($address_id);
					$this->success(L('_OPERATION_SUCCESS_'), url('partner/customer'));
				}else{
					$this->error(L('_OPERATION_FAIL_'));
				}
			}else{

				$countryList = SiteModel::get_country_list();
				$this->assign('countryList', $countryList);

//				$addressList = UserModel::get_address_list($user['id'], array('orderby' => 'id desc'));

				$where = array(
                    'user_id' => $user['id'],
					);

				$searchType = $this->_REQUEST('searchType');
				$keywords = $this->_REQUEST('keywords');
				if($searchType && $keywords){
                    switch ($searchType) {
                    	case 'email':
                    		$where['delivery_email'] = array('like','%'.trim($keywords).'%');
                    		break;
                    	case 'name':
                    	    $where['_string'] = 'delivery_first_name like "%'.trim($keywords).'%"';
                    		break;
                    	case 'phone':
                    		$where['delivery_phone'] = array('like','%'.trim($keywords).'%');
                    		break;                    		                    	
                    	default:
                    		break;
                    }
				}
                $this->assign('searchType', $searchType);
                $this->assign('keywords', $keywords);

				//分页显示数
				$limit_number = 10;
				
				$address_db = D('user_address');
				$address_count = $address_db->where($where)->count();
				require THEMES_PATH.'page.php';// 导入分页类
				$Page = new Page($address_count, $limit_number);// 实例化分页类 传入总记录数和每页显示的记录数
				$pageShow = $Page->show();// 分页显示输出
				$addressList = $address_db->where($where)->order('id desc')->
				               limit($Page->firstRow,$Page->listRows)->select();
				foreach ($addressList as $key => $val) {
			        //订单数查询
			        $orderWhere = array(
			            'order_status' => array('neq',OrderModel::ORDER_DEL),
			            'user_id' => $user['id'],
			            'address_id' => $val['id'],
			        	);
                    
                    //订单数量查询
					$order_count = OrderModel::get_order_count($orderWhere);
					$addressList[$key]['order_count'] = $order_count;
			        //订单金额查询
			        $orderField = 'sum(order_amount) as order_amount';
					$order_field = OrderModel::get_order_field($orderWhere, $orderField);
					$addressList[$key]['order_amount'] = floatval($order_field['order_amount']);			
				}
				$this->assign('pageShow', $pageShow);
				$this->assign('addressList', $addressList);
				//echo M()->getLastSql();exit;
				// echo '<pre />';
				// print_r($addressList);
				// exit;
				$templatefile = THEMES_PATH.'partner/partner_customer_list.phtml';
				$this->assign('templatefile', $templatefile);
                $this->display('usercenter');
			}
		}else{
			redirect($src ? base64_decode($src) : url('partner/login'));		
		}
	}
	
	//添加编辑配送地址
	public function customer_detail()
	{
		global $user;
		
		$this->checklogin();
		
		$aid = intval($_GET['addrid']);
		
		if($_POST['dosubmit']){
				if(UserModel::update_user_address($user['id'], $_POST)){
				$this->success(L('_OPERATION_SUCCESS_'), url('partner/customer'));
			}else{
				$this->error(L('_OPERATION_FAIL_'));
			}
		}else{
			$address = array();

			//成衣数据
            $size_type = C('size_type');
            foreach ($size_type as $key => $val) {
                $eidt_array[] = NULL; //修改数据的样式数组
                $eidt_array[] = 'timeData'; //修改数据的样式数组
                $eidt_array[] = 'button'; //修改数据的样式数组

                $size_name = D('size_name')
                    ->where(array('size_type' => $val['id'], 'display' => 0))
                    ->order('sort asc')
                    ->select();

                $size_type[$key]['size_name'] = $size_name;
            }
            $this->assign('size_type', $size_type);




			if($aid){
				$address_db = D('user_address');
				$address = $address_db->find($aid);
	            $measureInfo = MeasureModel::get_measure_one(array('address_id'=>$aid));

                $result['status'] = 1;
                if(isset($measureInfo['size_measure'])){
                    $size_measure = unserialize($measureInfo['size_measure']);
                }else{
                    $size_measure = [];
                }
                $this->assign('size_measure', $size_measure);


                //获取身型字段 兼容原先代码
		        $measure_field = MeasureModel::user_measure_field();
		        foreach ($measure_field as $key => $val) {
		            $value = $measureInfo[$val['measure_field']];
		            if ($val['measure_field'] == 'age') {
		                $new_measure_data[$val['measure_field']] = $value;
		            } else {
		                $new_measure_data[$val['measure_field']][$val['field_type']] = $value;
		            }
		        }
		        $new_measure_data['id'] = $measureInfo['id'];

		        $m_unit = $measureInfo['m_unit'] == 2 ? 'lbs': 'cm';
		        $this->assign('address', $address);
			    $this->assign('measure', $new_measure_data);
			    $this->assign('m_unit', $m_unit);
			    // print_r('<pre />');
			    // var_dump($new_measure_data);exit;
                //订单列表
				$post = array_merge($_GET,$_POST);
		        $where['orders.order_status'] = array('neq','-2'); 
				$where['orders.user_id'] = $user['id'];
				$where['orders.address_id'] = $aid;
				if($post['order_status'] != ''){
					$where['order_status'] = intval($post['order_status']);
				}
				if($post['payment_status'] != ''){
					$where['payment_status'] = intval($post['payment_status']);
				}
				if($post['shipping_status'] != ''){
					$where['shipping_status'] = intval($post['shipping_status']);
				}
				if($post['order_sn'] != ''){
					$where['order_sn'] = trim($post['order_sn']);
				}
				if($post['start_time']){
					$where['start_time'] = array('gt', strtotime($post['start_time']));
				}
				if($post['end_time']){
					$where['start_time'] = array('lt', strtotime($post['end_time']));
				}
				$order_db = D('orders');
				$order_item_db = D('orders_items');
				
				//分页
				$order_db->where($where);
				$count = $order_db->count();//总记录数
				require THEMES_PATH.'page.php';// 导入分页类
				$Page = new Page($count,15);// 实例化分页类 传入总记录数和每页显示的记录数
				$pageShow = $Page->show();// 分页显示输出
				$this->assign('pageShow', $pageShow);
				
				$order_db->field('orders.id,order_sn,order_amount,
					pay_amount,order_status,payment_status,shipping_status,
					start_time, comment.id as is_comment, payment_method,
					delivery_first_name,delivery_last_name,delivery_email,
					delivery_phone,delivery_mobile,delivery_cid,delivery_pid,
		            delivery_country,delivery_province,delivery_city,delivery_address,
		            delivery_address2,delivery_address3,delivery_postcode,delivery_time,
		            delivery2_first_name,delivery2_last_name,delivery2_email,delivery2_phone,
		            delivery2_cid,delivery2_country,delivery2_province,delivery2_city,
		            delivery2_address,delivery2_address2,delivery2_address3,delivery2_postcode');
				$order_db->order('orders.id DESC');
				$order_db->limit($Page->firstRow.','.$Page->listRows);
				$order_db->join('`comment` ON comment.order_id = orders.id');
				$order_db->group('orders.id');
				$order_db->where($where);
				$ordersList = $order_db->select();
				// echo M()->getLastSql();
				// var_dump($ordersList);exit;
				if($ordersList){
					foreach ($ordersList as &$row){
						
						$order_item_db->field('product.yushou_end_time,product.weikuan_time,product.product_type,car_type');
						$order_item_db->join('product ON product.id = orders_items.product_id');
						$order_item_db->where(array('order_id' => $row['id']));
						$productInfo = $order_item_db->find();
						if($productInfo){
							$row['yushou_end_time'] 	= $productInfo['yushou_end_time'];
							$row['weikuan_time'] 		= $productInfo['weikuan_time'];
							$row['product_type'] 		= $productInfo['product_type'];
							$row['car_type'] 			= $productInfo['car_type'];
						}
						$pay_return_db = D('orders_pay_return');
						$returnInfo = $pay_return_db->where('order_sn="'.$row['order_sn'].'" AND car_type=1')->find();
						//判断是否已申请退款
						if($returnInfo){
							$row['pay_return'] = 1;
							if($returnInfo['status']==2)
								$row['return_status'] = L('refunded');//已退款
							else
								$row['return_status'] = L('a_refund_of');//退款中
						}else{
							$row['pay_return'] = 0;
						}
						//支付按钮
						if(!in_array($row['order_status'], array(OrderModel::ORDER_CANCELED, OrderModel::ORDER_DEL))
							    && $row['payment_status'] == OrderModel::PAY_UNPAYED ){
		                    $paymentSubmit  = '';
		                    $paymentSubmit .= '<form id="frm" method="post" action="'.url('cart/ordersuccee',array('oid'=>$row['id'])).'" target="_blank">';
							$paymentSubmit .= '<input class="pay_button" type="submit" value="'.L('_PAY_NOW_').'">';
							$paymentSubmit .= '</form>';
							$row['paymentSubmit'] = $paymentSubmit;
						}
						if($row['order_status'] == OrderModel::ORDER_COMPLETE){
		                   $orders_items = D('orders_items')->field('id')->where(array('order_id'=>$row['id']))->select();
		                   $row['add_comment'] = false;
						   foreach ($orders_items as $orders_items_id) {
						        //是否评论过
						        $comment_where = array(
						        	'order_items_id'=>$orders_items_id['id'],
						        );
						        $comment_res = M('comment')->where($comment_where)->count();
						        if(!$comment_res){
						        	$row['add_comment'] = true;break;
						        }
						   }
						}
					}
					unset($row);
				}
				$this->assign('ordersList', $ordersList);

			}
			$countryList = SiteModel::get_country_list();
			$this->assign('countryList', $countryList);
//			$this->display('address_form');
			$templatefile = THEMES_PATH.'partner/partner_customer_detail.phtml';
			$this->assign('templatefile', $templatefile);
			$this->display('usercenter');
		}
	}
    
    //配送地址修改
	function customer_edit(){
		global $user;
		if(UserModel::logged()){
			if($_POST['dosubmit']){
				$post = $_POST;
                UserModel::update_user_address($user['id'], $post);
                $post['measure_name'] = $post['delivery_first_name'].' '.$post['delivery_last_name'];
                MeasureModel::edit_measure_data($post, $post['mid']);
				redirect(url('partner/customer_detail',array('addrid'=>$post['address_id'])));
                //$this->success(L('_OPERATION_SUCCESS_'), url('partner/customer_detail',array('addrid'=>$post['address_id'])));
			}else{
				redirect(url('partner/customer'));	
			}
		}else{
			redirect(url('partner/login'));		
		}	
	}  

	/**
	 * 检测是否登录
	 */
	private function checklogin()
	{
		if(! UserModel::logged()){
			$this->error(L('_USER_NO_LOGINED_'), url('partner/login'));
		}
	}
	
	/**
	 * 编辑订单信息
	 */
	public function edit_order()
	{
		global $user;
		$this->checklogin();
		$post = $_POST;
		$product_amount = isset($post['product_amount']) ? floatval($post['product_amount']) : 0;
		$product_dingjin = isset($post['product_dingjin']) ? floatval($post['product_dingjin']) : (isset($post['dingjin']) ? floatval($post['dingjin']) : 0);
		$payment_fee = isset($post['payment_fee02']) ? floatval($post['payment_fee02']) : 0;
		$shipping_fee = isset($post['shipping_fee']) ? floatval($post['shipping_fee']) : 0;
		$surplus_money = isset($post['surplus_money02']) ? floatval($post['surplus_money02']) : 0;
		$hongbao_money = isset($post['hongbao_money']) ? floatval($post['hongbao_money']) : 0;
		$integral_money = isset($post['integral_money']) ? floatval($post['integral_money']) : 0;
		$hongbao_id = isset($post['hongbao_id']) ? floatval($post['hongbao_id']) : 0;
		
		//添加到订单表
		$order_db = D('orders');
		$post['delivery_cid'] = intval($post['delivery_cid']);
		$post['delivery_pid'] = intval($post['delivery_pid']);
		$data = array(
			'shipping_method' => $post['shipping_method'],
			'payment_fee' => floatval($post['payment_fee']),
			'shipping_fee' => floatval($post['shipping_fee']),
			'delivery_first_name' => trim($post['delivery_first_name']),
			'delivery_last_name' => trim($post['delivery_last_name']),
			'delivery_phone' => trim($post['delivery_phone']),
			'delivery_mobile' => trim($post['delivery_mobile']),
			'delivery_postcode' => trim($post['delivery_postcode']),
			'delivery_cid' => $post['delivery_cid'],
			'delivery_province' => isset($post['delivery_province']) ? trim($post['delivery_province']) : null,
			'delivery_city' =>  isset($post['delivery_city']) ? trim($post['delivery_city']) : null,
			'delivery_address' =>  isset($post['delivery_address']) ? trim($post['delivery_address']) : null,
			'product_dingjin' => $product_dingjin,
			'surplus_money' => $surplus_money,
			'hongbao_money' => $hongbao_money,
			'integral_money' => $integral_money,
		);
		if($post['product_amount']){
			$data['product_amount'] = $post['product_amount'];
		}
		
		if($post['payment_status'] == 4){
			$data['payment_method2'] = $post['payment_method'];
		}else{
			$data['payment_method'] = $post['payment_method'];
		}
		//更新国家
		if($post['delivery_cid']){
			$area_info = SiteModel::get_region_info($post['delivery_cid']);
			if($area_info){
				$data['delivery_country'] = $area_info['name'];
			}
		}
		
		//订单总费用
		$order_amount = $product_amount + $payment_fee + $shipping_fee;
		$data['order_amount'] = $order_amount;
		
		//应付费用
		$pay_amount = $order_amount - $surplus_money - $hongbao_money - $product_dingjin - $integral_money;
		$data['pay_amount'] = $pay_amount;
		
		$result = $order_db->where(array('id' => $post['oid']))->save($data);
		
		
		//扣除会员的余额
		if($surplus_money && $user['id']){
			UserModel::log_account_change($user['id'],(-1)*$surplus_money,0,0,0,L('_ORDER_USE_BALANCE_PAYMENT_').' '.L('_THE_ORDER_NUMBER_IS_').' '.$post['order_sn'],UserModel::ACT_PAY);
		}
		
		//减去会员支付使用的积分
		if($user['user_id'] && $integral_money){
			UserModel::log_account_change($user['user_id'],0,0,0,(-1)*$integral_money,L('_ORDER_REFUND_').' '.L('_THE_ORDER_NUMBER_IS_').' '.$post['order_sn'],UserModel::ACT_REFUND);
		}
		
		
		//更新订单各种费用
		if($post['chima'] != '' && $post['payment_status'] == 0)
			OrderModel::update_order_prices02($post['oid']);
		else
			OrderModel::update_order_prices($post['oid']);
		
		//发送下单邮件
		$orderInfo = OrderModel::get_order_info($post['oid']);
		$mailInstance = new EmailModel();
		$email_template = UserModel::get_email_template_info('orderTradingEmail', $orderInfo['language_id']);
		if($email_template){
			$orderInfo['productList'] = OrderModel::get_order_product_list($post['oid']);
			$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
			$title = $mailInstance->replaceMail($email_template['title']);
			$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
		}
		
		//支付通知邮件
		if(floatval($orderInfo['pay_amount'])==0){
			$email_template = UserModel::get_email_template_info('orderPayEmail', $orderInfo['language_id']);
			if($email_template){
				$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
				$title = $mailInstance->replaceMail($email_template['title']);
				$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content,'html','bcc');
			}
		}
		
		//删除相应的红包
		if($hongbao_id > 0){
			
			$user_bonus_db = D('user_bonus');
			$data02 = array(
				'bonus_sn' => $post['order_sn'],
				'used_time' => time(),
			);
			$user_bonus_db->where('id='.$hongbao_id)->save($data02);
			
			$bonus_db = D('bonus_type');
			$bonusInfo = $bonus_db->field('id,min_amount,send_start_date,send_end_date')->where('send_type=1')->find();
			//判断红包是否在发送期间
			if(time() >= $bonusInfo['send_start_date'] && time() <= $bonusInfo['send_end_date']){
				if($order_amount > $bonusInfo['min_amount']){
					$data = array(
						'bonus_id' => intval($bonusInfo['id']),
						'bonus_sn' => 0,
						'user_id' => intval($user['id']),
						'used_time' => 0,
						'order_id' => 0,
						'emailed' => 0,//1：已发成功；0未成功
						'time' => time(),
					);
					$user_bonus_id = $user_bonus_db->add($data);	
				}
			}
	
		}
		
		redirect(url('cart/ordersuccee', 'oid='.$post['oid']));
	}

	//退换货申请
	public function request()
	{
		global $user;
		$data = array(
			// 'docTitle' => L('meta_title_address_list'),
			// 'docKeywords' => L('meta_keywords'),
			// 'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		if(UserModel::logged()){
			$_SESSION['center_type'] = 101;
			if($_POST['dosubmit']){
				$post = $_POST;
				$orderInfo = OrderModel::get_oreder_info_by_order_sn($post['order_sn']);
				if(!$orderInfo){
					$this->error(L('_OPERATION_FAIL_'));exit;
				}
				$data['order_id'] = $orderInfo['id'];
				$data['product_name'] = $post['product_name'];
				$data['order_sn'] = $post['order_sn'];
				$data['description'] = $post['description'];
				$data['user_id'] = $user['id'];
				$data['status'] = 1;

				$data['contact_name']  = $orderInfo['delivery_first_name'].' '.$orderInfo['delivery_last_name'];
				$data['contact_phone'] = $orderInfo['delivery_phone'];
				$data['contact_email'] = $orderInfo['delivery_email'];

				$pid = OrderModel::insert_purchase_info($data);				
				if($pid){
					$this->success(L('_OPERATION_SUCCESS_'), url('partner/request'));
				}else{
					$this->error(L('_OPERATION_FAIL_'));
				}
			}else{
				$templatefile = THEMES_PATH.'partner/partner_alteration_request.phtml';
				$this->assign('templatefile', $templatefile);
			}
		}else{
			redirect($src ? base64_decode($src) : url('partner/login'));		
		}
		$this->display('usercenter');
	}

	//退换货申请 中的地址
	public function request_ajax()
	{
		global $user;
		$error = 1;
		$info = '';
		if(UserModel::logged()){
				$order_sn = $_REQUEST['order_sn'];
				$orderInfo = OrderModel::get_oreder_info_by_order_sn($order_sn);
				if($orderInfo && $orderInfo['user_id'] == $user['id']){
					$info = '';
	                $info .='<li><strong>Name:</strong> <span>'.$orderInfo['delivery_first_name'].' '.$orderInfo['delivery_last_name'].'</span></li>';
	                $info .='<li><strong>Email:</strong> <span>'.$orderInfo['delivery_email'].'</span></li>';
	                $info .='<li><strong>Phone:</strong> <span>'.$orderInfo['delivery_phone'].'</span></li>';
	                $info .='<li><strong>Address:</strong> <span>'.$orderInfo['delivery_address'].' '.$orderInfo['delivery_address2'].' '.$orderInfo['delivery_city'].' '.$orderInfo['delivery_province'].' '.$orderInfo['delivery_country'].' '.$orderInfo['delivery_postcode'].'</span></li>';
				}else{
                    $error = 0;
				}				
		}else{
            $error = '-1';
		}
        $result = array(
            'error' => $error,
            'info' => $info,
        	);
		echo json_encode($result);
	}


	//留言
	public function feedback()
	{
		global $user;
		$data = array(
			'docTitle' => L('meta_title_address_list'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);		
		//$this->checklogin();
		if(UserModel::logged()){
			$_SESSION['center_type'] = 103;
			if($_POST['dosubmit']){
                
                $message = $_POST['message'];

	                //内部邮件
                $sendMail = 'service@ownonly.com';
                $title = 'Partner Feedback';
                $content  = 'Name:'.$user['name'].'<br />';
				$content .= 'Email:'.$user['email'].'<br />';
				$content .= 'Message:'.$message.'<br />';
				$post = array(
					'message_type' => 1,
					'title' => 'Partner Feedback',
					'content' => $message,
				);
				if(CommentModel::insert_guestbook($post)){
					$mailInstance = new EmailModel();
					$mailInstance->sendMail($sendMail, $title, $content);						
				    $this->success(L('_OPERATION_SUCCESS_'), url('partner/feedback'));
				}else{
					$this->error(L('_OPERATION_FAIL_'));
				}
			}else{
				$templatefile = THEMES_PATH.'partner/partner_feedback.phtml';
				$this->assign('templatefile', $templatefile);
				$this->display('usercenter');
			}
		}else{
			redirect($src ? base64_decode($src) : url('partner/login'));
			$this->display('usercenter');
		}
		
	}

    //下单页面
	function order_add(){
		global $user;

		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
		header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); 
		header("Cache-Control: no-cache, must-revalidate"); 
		header("Pramga: no-cache"); 

		$data = array(
			'docTitle' => L('meta_title_address_list'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$size_type = C('size_type');
		foreach ($size_type as $key => $val) {
			$eidt_array[] = NULL; //修改数据的样式数组
			$eidt_array[] = 'timeData'; //修改数据的样式数组
			$eidt_array[] = 'button'; //修改数据的样式数组

			$size_name = D('size_name')
				->where(array('size_type' => $val['id'], 'display' => 0))
				->order('sort asc')
				->select();

			$size_type[$key]['size_name'] = $size_name;
		}
		$this->assign('size_type', $size_type);
		$this->assign($data);		
		//$this->checklogin();
		if(UserModel::logged()){

			    $this->assign('addrid', $_REQUEST['addrid']);
                //国家列表
                $countryList = SiteModel::get_country_list();
				$this->assign('countryList', $countryList);

				$templatefile = THEMES_PATH.'partner/partner_order_add.phtml';
				$this->assign('templatefile', $templatefile);
		}else{
			redirect($src ? base64_decode($src) : url('partner/login'));		
		}
		$this->display('usercenter');	    
	}
	
	//老客户列表
    function customer_list_ajax(){
		global $user;
		if(UserModel::logged()){
	        $where = array(
	        	'user_id'=>$user['id'],
	        );
 
			$keywords = trim($this->_REQUEST('keywords'));
			if($keywords){
				//邮箱
        		$where['_string'] = ' delivery_email like "%'.$keywords.'%"';
        		//电话
        		$where['_string'] .= ' or delivery_phone like "%'.$keywords.'%"';
        	    //姓名
        	    $names = explode(' ', $keywords);
        	    if(isset($names[1])){
        		    $where['_string'] .= ' or (delivery_first_name like "%'.trim($names[0]).'%"';
        		    $where['_string'] .= ' and delivery_last_name like "%'.trim($names[1]).'%")';
        	    }else{
        	    	$where['_string'] .= 'or delivery_first_name like "%'.trim($names[0]).'%" ';
        	    	$where['_string'] .= ' or delivery_last_name like "%'.trim($names[0]).'%"';
        	    }
			}           

	        $order = "id desc";
	        $pageRows = 5;
			$address_db = D('user_address');
			$count = $address_db->where($where)->count();
			import("ORG.Util.PageListSimple");
			$Page = new Page($count,$pageRows);
			$pageShow = $Page->show();
			$addressList = $address_db->where($where)->order($order)
			               ->limit($Page->firstRow.','.$Page->listRows)->select();
			//echo M()->getLastSql();exit;
            //measure
			$user_measure_db = M('user_measure');               
			foreach ($addressList as $key => $val) {
                $addressList[$key]['age'] = $user_measure_db->where($where)->getField('age');
			}               
	        $pageShow = preg_replace("/\/_\/(\d+)'/is", "'", $pageShow);
            $pageShow = preg_replace("/href='\/partner\/customer_list_ajax(\/keywords\/([^\/]*))?\/p\/(\d+)'/is", "href='javascript:;' data='$2' onclick='showCustomer($3);'", $pageShow);
		  	//var_dump($pageShow);exit;  
		}

		$this->assign('pageShow', $pageShow);
		$this->assign('addressList',$addressList);
		$this->display('partner_customer_list_ajax');
    }
    
    //老客户的数据
    public function customer_res_ajax(){
		global $user;
		if(UserModel::logged()){
			$address_id = $this->_post('customerid');
			//查询address地址
	        $address = UserModel::get_address_info($address_id);
	        $measureInfo = MeasureModel::get_measure_one(array('address_id' => $address_id));
	        if($address && $measureInfo){
	            $result['status'] = 1;
				if(isset($measureInfo['size_measure'])){
					$measureInfo['size_measure'] = unserialize($measureInfo['size_measure']);
				}
	            $result['data'] = array_merge($address,$measureInfo);

            }else{
            	$result['status'] = 0;
            }
		}else{
            $result['status'] = 0;
		}
        echo json_encode($result);
    }
    //选择商品
    public function product_add(){
		global $user, $language_id;		
		$pid = intval($_GET['pid']);
		$productInfo = ProductModel::get_product_info($pid);
		$result = array(
            'error' => '0',
            'errstr' => '0',
			);
		if(!$productInfo || $productInfo['display'] == 0){
			$result['errstr'] = L('_PRODUCT_NO_EXIST_');
		}else if($productInfo['attribute_type'] != 2){
		    $result['error'] = 1;   //普通商品，直接添加
		}/*else if($productInfo['model_id'] == 25){
		    $result['error'] = 3;  //鞋子，属于定制商品，但没有快捷购买
		}*/else{
		    $result['error'] = 2;  //定制商品
		    $result['sizeRes'] = $this->get_product_size($pid);
		}
		echo json_encode($result);
		// $url = url('product/rewrite_custom').'/partner/1/id/'.$pid;
		// if($cid) $url .= '/cid/'.$cid;
	    // redirect($url);
    }
    
    //根据产品类型查出 --选尺码购物
    public function get_product_size($pid){
        if($_POST['ajax']){
        	$pid = $_POST['pid'];
        }
    	$product = ProductModel::get_product_info($pid);
        if($product['attribute_type'] == 2){
			//根据产品类型查出 --选尺码购物
			$size_type_arr = C('m_data');
	        //礼服特殊处理
			if($product['model_id'] == 23){
				$cat_parentid = CategoryModel::get_category_parentid($product['catid']);
				if($product['catid'] == 2061 || $cat_parentid == 2061){
	                  $product['model_id'] = 233;
				}else{
					  $product['model_id'] = 232;
				}
			}
			$size_type = $size_type_arr[$product['model_id']];
			$size_type_res = array();
			foreach ($size_type as $key => $val) {
				$notm_where = array(
	                'size_type' => $val,
					);
				$size_data_notm = D('size_data_notm')->field('DISTINCT(size)')
				                  ->where($notm_where)->select();
				$size_type_res[$val] = $size_data_notm;
			}
            
            $key_k = 1;
            $getSizeRes = array();
            foreach($size_type_res as $key=>$sizeRes){
            	$sizeRes_one = array();
	            if($key == 1){
	              $data_type = "blazers";
	              $data_name = L('Jacket_Size');
	              $data_type_name = L('_JACKETS_');
	            }
	            if($key == 2){
	              $data_type = "vests";
	              $data_name = L('Vest_Size');
	              $data_type_name = L('_VESTS_');
	            }
	            if($key == 3){
	              $data_type = "pants";
	              $data_name = L('Pant_Size');
	              $data_type_name = L('_PANTS_');
	            }
	            if($key == 4){
	              $data_type = "shirts";
	              $data_name = L('Shirt_Size');
	              $data_type_name = L('_SHIRTS_');
	            }
	            if($key == 5){
	              $data_type = "coats";
	              $data_name = L('Coat_Size');
	              $data_type_name = L('_COATS_');
	            }
	            $sizeRes_one['typeid']   = $key;
	            $sizeRes_one['type'] = $data_type;
                $sizeRes_one['name'] = $data_name;
                $sizeRes_one['size'] = array();
	            foreach($sizeRes as $val){
	                $sizeRes_one['size'][] = $val['size'];
	            }
	            $key_k++;
	            $getSizeRes[] = $sizeRes_one;
            }	            
		}
        if($_POST['ajax']){
        	echo json_encode($getSizeRes);
        }else{
        	return $getSizeRes;
        }
		
    }

     //购物车显示
    public function cart(){
		global $user, $language_id;
        
		$shipping_method_val = trim($_GET['shipping_method_val']);
		$payment_method_val = trim($_GET['payment_method_val']);
		$delivery_cid = intval($_GET['delivery_cid']);
		$userweight   = floatval($_GET['userweight']);
		$this->assign('shipping_method_val', $shipping_method_val);
		$this->assign('payment_method_val', $payment_method_val);

		$cartProductList = CartModel::get_cart_product_list_partner();
		//支付方式
		$paymentList = PaymentModel::get_payment_list();
		$this->assign('paymentList', $paymentList);
		//配送方式
		$shippingList = ShippingModel::get_shipping_list();
		$this->assign('shippingList', $shippingList);
        
        if(!$shipping_method_val){
            foreach ($shippingList as $key=>$shipping){
                if (!$shipping['status']) continue;
                $shipping_method_val = $shipping['name'];
                break;
            }
        }

        //支付费用 (超重费用计入 20150714)
        $payment_fee = PaymentModel::get_paymeent_fee($payment_method_val, $cartProductList['total_number'], 1, $userweight);
        $this->assign('payment_fee', $payment_fee);
        $total_amount = $cartProductList['total_amount'] + $payment_fee;

        //用户折扣率
        $hongbao_money = 0;
        if(UserModel::logged()){
            $discount = UserModel::get_rank_discount($user['rank_id']);
            $hongbao_money = $total_amount * (1-$discount);
        }
        $this->assign('hongbao_money', $hongbao_money);
        //配送费用
        $shipping_fee = ShippingModel::get_shipping_fee($shipping_method_val, $delivery_cid, $cartProductList['total_amount'], $cartProductList['total_weight'], $cartProductList['total_number']);
        $this->assign('shipping_fee', $shipping_fee);

		$this->assign('cartInfo', $cartProductList);
		if($_REQUEST['cart_mode']=='parener_cart_ajax'){
			$this->display('partner_ajax_cart');
		}else{
			$this->display('partner_cart');
		}
	}

}